package trader.orig;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class Util {
    public static final String BASE_URL = "http://sv-demotrader-01.x.ngm.se";
    public static final String MAIL = "jonas.westman@ngm.se"; //change
    public static final String PASSWORD = "apa"; //change
    public static final String USER_ID = "32"; //change
    public static String sessionId;
    public static final int[] PORTFOLIOS = {109, 110, 111, 112}; //change
    public static final Map<String, OwnedInstrument> portfolio = Collections.synchronizedMap(new HashMap<String, OwnedInstrument>());
    public static final Map<String, SoughtInstrument> sought = Collections.synchronizedMap(new HashMap<String, SoughtInstrument>());
    public static final Map<String, Limit> limits = Collections.synchronizedMap(new HashMap<String, Limit>());
    public static final Map<String, Poller> pollers = Collections.synchronizedMap(new HashMap<String, Poller>());
    public static JSONParser parser = new JSONParser();
    
    public static Object fromJSon(String json) {
        Object obj = null;
        synchronized (parser) {
            try {
                obj = parser.parse(json);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return obj;
    }
    
    public static boolean login(String mail, String password) throws IOException {
        BufferedReader in = null;
        try {
            URL url = new URL(Util.BASE_URL + "/profile/login.php");
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = "";
            String magic = "";
            while ((line = in.readLine()) != null) {
                line = line.trim();
                if (line.startsWith("var enqrypted_pwd")) {
                    magic = line.substring(line.indexOf("\"") + 1, line.lastIndexOf("\""));
                    break;
                }
            }
            
            boolean done = false;
            for (String key : conn.getHeaderFields().keySet()) {
                if (key != null && key.equals("Set-Cookie")) {
                    for (String s : conn.getHeaderFields().get(key)) {
                        if (s.startsWith("PHPSESSID")) {
                            Util.sessionId = s;
                            done = true;
                        }
                    }
                }
                if (done) {
                    break;
                }
            }
            
            in.close();
            
            url = new URL(Util.BASE_URL + "/scripts/php/data/profile.php");
            conn = (HttpURLConnection)url.openConnection();
            String data = "action=login&email=" + mail + "&pwd=" + sha1(magic + sha1(mail + password));
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Length", "" + data.length());
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Cookie", Util.sessionId);
            conn.setDoOutput(true);
            OutputStream out = conn.getOutputStream();
            out.write(data.getBytes());
            out.close();
            
            conn.connect();
            
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            line = "";
            while ((line = in.readLine()) != null) {
                //System.out.println(line);
                JSONObject obj = (JSONObject)Util.fromJSon(line);
                String message = (String)obj.get("message");
                if (message.equalsIgnoreCase("ok")) {
                    return true;
                }
            }
            return false;
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }
    
    private static String sha1(String data) {
        MessageDigest md;
        byte[] bytes = null;
        try {
            md = MessageDigest.getInstance("SHA1");
            md.update(data.getBytes());
            bytes = md.digest();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
        
        String hash = "";
        for (byte b : bytes) {
            String s = Integer.toHexString(b & 0xFF);
            if (s.length() == 1) {
                s = "0" + s;
            }
            hash += s;
        }
        
        return hash;
    }
    
    public static boolean buy(String oid, double price, int volume, int portfolio) {
        try {
            URL url = new URL(Util.BASE_URL + "/scripts/php/data/trade.php");
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            String data = "action=buy_request&id=" + oid + "&price=" + price + "&volume=" + volume + "&portfolio=" + portfolio;
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Cookie", Util.sessionId);
            conn.setDoOutput(true);
            OutputStream out = conn.getOutputStream();
            out.write(data.getBytes());
            out.close();
            String line = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line = in.readLine()) != null) {
                //System.out.println(line);
                JSONObject obj = (JSONObject)Util.fromJSon(line);
                String message = (String)obj.get("message");
                if (message.equalsIgnoreCase("ok")) {
                    return true;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Buy of " + oid + " failed");
            return false;
        }
        return false;
    }
    
    public static boolean sell(String id, String internalId, double price, int volume) {
        try {
            URL url = new URL(Util.BASE_URL + "/scripts/php/data/trade.php");
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            String data = "action=sell_request&usr_id=" + Util.USER_ID + "&instrument_id=" + id + "&content_id=" + internalId + "&price=" + price + "&volume=" + volume;
            System.out.println(data);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Cookie", Util.sessionId);
            conn.setDoOutput(true);
            OutputStream out = conn.getOutputStream();
            out.write(data.getBytes());
            out.close();
            String line = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line = in.readLine()) != null) {
                //System.out.println(":" + line);
                if (line.equals("")) {
                    continue;
                }
                //System.out.println("HELLO: " + Util.fromJSon(line).getClass());
                JSONObject obj = (JSONObject)Util.fromJSon(line);
                String message = (String)obj.get("message");
                if (message.equalsIgnoreCase("ok")) {
                    return true;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Sell of " + id + " failed");
            return false;
        }
        return false;
    }
}
